package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

//用户地址
@RestController
public class AddressController {

    @Autowired
    private AddressService addressService;

    @Autowired
    private CartService cartService;

    //查询地址列表
    @GetMapping("/address/list")
    public ResultInfo findList() {
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }

    //地址新增
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address) {
        addressService.save(address);
        return ResultInfo.success(null);
    }

    //设置默认地址
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody Map<String, Long> map) {
        //1.接受参数 地址id
        Long id = map.get("id");

        //2.调用service设置
        addressService.setDefault(id);

        //3.返回结果
        return ResultInfo.success(null);
    }

    //查询默认地址
    @GetMapping("/address/default")
    public ResultInfo findDefault() {
        Address address = addressService.finDefault();
        if (address != null) {
            return ResultInfo.success(address);
        } else {
            return ResultInfo.error("没有默认地址");
        }

    }

    //修改购物车
    @PostMapping("/cart/sub")
    public ResultInfo update(@RequestBody Cart cartPram) {
        Cart cart = cartService.update(cartPram);
        return ResultInfo.success(cart);
    }

    /**
     * 根据主键查询
     */
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Address address = addressService.findById(id);
        return ResultInfo.success(address);
    }

    /*
     * 修改地址
     * */
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address) {
        addressService.update(address);
        return ResultInfo.success(null);
    }

    /*
     * 删除地址
     * */
    @DeleteMapping("/address")
    public ResultInfo deleteById(Long ids) {
        addressService.deleteById(ids);
        return ResultInfo.success(null);
    }
}
